import {action, asMap, observable, toJS} from 'mobx';
import base from './../util/base';
import * as type from './../constants/type';
import {doSubmitForm} from './../util/submit'
import * as API from './../apis/req'
import * as _ from '../util/public/common';
import {message} from "antd";
import {getAntd, getComsMobx} from '../util/convert';


export class FreeWorkflowNew {

  @observable nodeList = [];
  @observable freeNodeDatas={};
  @observable freeStartNodeid = 0;
  @observable freeEndNodeid = 0;
  @observable createNodeDatas = [];
  @observable currentGroupId = "";
  @observable currentnodeid = 0;
  @observable signType = "2";
  @observable selectedPersons = {};
  @observable oprateNodeId = 0;
  @observable isEdit = 0;
  @observable createNodeid = 0;
  @observable FreeNodeList = [];
  @observable addNodePosition = 0;
  @observable deleteNodePosition = 0;
  @observable maxGroupNum = 0;
  @observable isadd = false;
  @observable deleteids = -1;
  @observable allowAddNewBranch = false
  @observable showSaveModalDialog = false;
  @observable modal={name:"",type:"0"};
  @observable showImportModalDialog = false;
  @observable showImportModalAdvance = false;
  @observable importModalStore = null;
  @observable importModelForm = null;
  @observable modelAdCondition = [];
  @observable modalName = "";
  @observable isFree = "";
  @observable loading = true;

  @observable xiebandata = "";
  
  @observable clickrequestid = "";
  @observable clicknodeid = "";
  @action
  setProperty=(map)=>{
    Object.assign(this,map);
  }

  @action
  getNodeList=()=>{
    this.loading = true;
    let {rightMenu,commonParam,baseParam} = base.globalStore;
    const { iscreate,authSignatureStr,authStr,wfTestStr,belongTest, selectNextFlowPattern} = toJS(commonParam);
    const { iscnodefree,isFree,freeNode = {} ,isAllowNodeFreeFlow} = toJS(rightMenu);
    const {nodeid,workflowid,requestid,f_weaver_belongto_userid,f_weaver_belongto_usertype} = toJS(baseParam);
    this.isFree = isFree;
    let params = {
      isFree,
      nodeid,
      workflowid,
      requestid,
      isAllowNodeFreeFlow,
      f_weaver_belongto_userid,
      f_weaver_belongto_usertype,
      wfTestStr,
      authSignatureStr,
      authStr,
      belongTest,
      showForecastNode:"",
      isFromHtmlPage:true,
      templateid:-1,
	  onlyNodeOperator:1,
    };
    API.getFreeNodeInfo(params).then(data=>{
      this.loading = false;
      this.initFreeNode(data);
      const {WeaTableNew,WeaForm} = getComsMobx();
      const {TableStore} = WeaTableNew;
      this.importModalStore = new TableStore();
      this.importModelForm = new WeaForm();
    })
  }

  @action
  initFreeNode=(data)=>{
    let {commonParam={},rightMenu={},setProperty} = base.globalStore;
    let {lastname,nodeid,currentnodeid,requestid=-1} = toJS(commonParam);
    let {szssz01={}} = rightMenu;
    let {createname="",createNodeid="",isEdit=0} = szssz01;
    let {freeNodeDatas={},currentStartNodeId,currentGroupId,nodeLinks={},maxGroupNum,allowAddNewBranch=false} = data;
    this.currentGroupId = currentGroupId;
    this.freeStartNodeid = createNodeid;
    this.currentnodeid = currentnodeid;
    this.createNodeid = createNodeid;
    this.isEdit = isEdit;
    this.allowAddNewBranch = allowAddNewBranch;
    this.maxGroupNum = maxGroupNum;
    this.xiebandata="";
    if(requestid>0){
      try{
        this.freeEndNodeid = nodeLinks[createNodeid][0].descnode;
      }catch(e){
          console.error(e);
      }
    
    }
    this.createNodeDatas = [{
      id:createNodeid,
      name:createname,
      haveviewed:true,
      isCurrent:true,
      notviewed:false
    }]
    if(!_.isEmpty(toJS(freeNodeDatas))){
      this.freeNodeDatas = toJS(freeNodeDatas)[createNodeid]?toJS(freeNodeDatas)[createNodeid][0]:{};
      setProperty({freeNodeDatas:this.getSubmitNodeList(toJS(this.freeNodeDatas),[])});
    }else {
      this.freeNodeDatas = {};
    }
  }

  @action
  addNextNode=()=>{
    this.isadd = true;
    let {rightMenu={},commonParam={},baseParam={}} = base.globalStore;
    const { iscreate,authSignatureStr,authStr,wfTestStr,belongTest, selectNextFlowPattern} = toJS(commonParam);
    const { iscnodefree,isFree,freeNode = {} ,isAllowNodeFreeFlow} = toJS(rightMenu);
    const {nodeid,workflowid,requestid,f_weaver_belongto_userid,f_weaver_belongto_usertype} = toJS(baseParam);
    let {szssz01={}} = rightMenu;
    let {createname="",createNodeid=""} = szssz01;
    let {ids,names,datas=[]} = toJS(this.selectedPersons);
    let freeNodeList = [];
    if(!_.isEmpty(toJS(this.freeNodeDatas))){
      freeNodeList = this.generateDatas(toJS(this.freeNodeDatas),[]);
    }
    freeNodeList = this.insertFreeDatas(freeNodeList);
    let chartDatas = this.generateParams(freeNodeList,{},0);
    let params = {
      addSigntype:this.signType,
      xiebandata:this.xiebandata,
      currentPostRequestId:"",
      currentPostWorkflowId:"",
      isFree,
      nodeid,
      workflowid,
      requestid,
      templateid: -1,
      isAllowNodeFreeFlow,
      f_weaver_belongto_userid,
      f_weaver_belongto_usertype,
      wfTestStr,
      authSignatureStr,
      authStr,
      belongTest,
      isFromHtmlPage: true,
      showForecastNode:"",
      maxGroupNum: this.maxGroupNum+datas.length,
      chartDatas:JSON.stringify(chartDatas)
    };

    API.saveFreeNodeInfo(params).then(data=>{
      this.getNodeList(toJS(this.freeNodeDatas),[]);
    })
  }

  @action
  getSubmitNodeList=(datas,temp)=>{
    let next = datas["next"];
    if(!_.isEmpty(next)){
      temp = [...temp,datas];
      return this.getSubmitNodeList(next,temp);
    }else {
      temp = [...temp,datas];
    }
    return temp;
  }

  @action
  deleteNode=(operatorReplaceDatas)=>{
    this.isadd = false;
    let {rightMenu={},commonParam={},baseParam={}} = base.globalStore;
    const { iscreate,authSignatureStr,authStr,wfTestStr,belongTest, selectNextFlowPattern} = toJS(commonParam);
    const { iscnodefree,isFree,freeNode = {} ,isAllowNodeFreeFlow} = toJS(rightMenu);
    const {nodeid,workflowid,requestid,f_weaver_belongto_userid,f_weaver_belongto_usertype} = toJS(baseParam);
    let {szssz01={}} = rightMenu;
    let {createname="",createNodeid=""} = szssz01;
    let {ids,names,datas=[]} = toJS(this.selectedPersons);
    let operators = operatorReplaceDatas.map(item=>item.name).join("，");
    let {Modal} = window.antd;
    let _that =this;
    Modal.confirm({
      title: '您是否确认要删除此节点',
      content: `节点操作者：${operators}`,
      onOk() {
        let freeNodeList = _that.generateDatas(toJS(_that.freeNodeDatas),[]);
        freeNodeList = _that.deleteFreeDatas(freeNodeList);
        let chartDatas = _that.generateParams(freeNodeList,{},0);
        let params = {
          currentPostRequestId:"",
          currentPostWorkflowId:"",
          isFree,
          nodeid,
          workflowid,
          requestid,
          templateid: -1,
          isAllowNodeFreeFlow,
          f_weaver_belongto_userid,
          f_weaver_belongto_usertype,
          wfTestStr,
          authSignatureStr,
          authStr,
          belongTest,
          isFromHtmlPage: true,
          showForecastNode:"",
          maxGroupNum: _that.maxGroupNum-1,
          chartDatas:JSON.stringify(chartDatas),
          deleteIds:_that.deleteids
        };

        API.saveFreeNodeInfo(params).then(data=>{
          _that.getNodeList();
        })
      },
      onCancel() {},
    });
  }
  @action
  generateDatas=(datas,temp)=>{
    let next = datas["next"];
    datas = {...datas,freeEndNodeid:this.freeEndNodeid, freeStartNodeid:this.freeStartNodeid};
    if(!_.isEmpty(next)){
      temp = [datas,...temp];
      return this.generateDatas(next,temp);
    }else {
      temp = [datas,...temp];
    }
    return temp;
  }

  @action
  insertFreeDatas=(freeDatas=[])=>{
    let arr= [];
    let {ids,names,datas=[]} = toJS(this.selectedPersons);
    let datasLen = datas.length;
    if(this.signType==1||datasLen==1||this.signType==7){//ylc
      let operator = ids.split(",").map(item=>"1_"+item).join(",");
      arr = [{
        id:-1*this.maxGroupNum,
        nodeElement:true,
        groupStatus: "0",
        freeEndNodeid:this.freeEndNodeid,
        freeStartNodeid:this.freeStartNodeid,
        hasNext:false,//待定
        next:null,
        preid:0,
        nextid:0,
        parallelNodeGroupDatas:[],
        nodeEntity:{
          "nodename": "节点"+this.maxGroupNum,
          "operatortype": "resource",
          "operatorids":ids,
          "operators": operator,
          "nodetype": "1",
          "mustPass": false,
          "signType": this.signType,
          "nextNodeEditPurview": "2",
          "allowForward": "1",
          "allowTransfer": "1",
          "allowComments": "1",
          "allowModify":true,
          "overflowtimetype": "0",
          "advanceRemind": "0",
          "isrejectremind": "0",
          "ischangrejectnode": "0",
          "isselectrejectnode": "1",
          "isSubmitDirectNode": "0",
          "overflowtimehour": 0,
          "overflowtimeminute": 0,
          "overtimeToNextOperator": "0",
          "afterLoopRemind": "0",
          "afterRemindInterval": "5",
          "beforeLoopRemind": "0",
          "beforeRemindInterval": "5"}
      }]
    }else {
      arr = datas.reverse().map((item,index)=>{
        return {
          id:-1*(this.maxGroupNum+(datasLen-index-2)),
          nodeElement:true,
          groupStatus: "0",
          freeEndNodeid:this.freeEndNodeid,
          freeStartNodeid:this.freeStartNodeid,
          hasNext:false,//待定
          next:null,
          preid:0,
          nextid:0,
          parallelNodeGroupDatas:[],
          nodeEntity:{
            "nodename": "节点"+(this.maxGroupNum+(datasLen-index-2)),
            "operatortype": "resource",
            "operatorids":item.id,
            "operators": "1_"+item.id,
            "nodetype": "1",
            "mustPass": false,
            "signType": this.signType,
            "nextNodeEditPurview": "2",
            "allowForward": "1",
            "allowTransfer": "1",
            "allowComments": "1",
            "allowModify":true,
            "overflowtimetype": "0",
            "advanceRemind": "0",
            "isrejectremind": "0",
            "ischangrejectnode": "0",
            "isselectrejectnode": "1",
            "isSubmitDirectNode": "0",
            "overflowtimehour": 0,
            "overflowtimeminute": 0,
            "overtimeToNextOperator": "0",
            "afterLoopRemind": "0",
            "afterRemindInterval": "5",
            "beforeLoopRemind": "0",
            "beforeRemindInterval": "5"}
        }
      })
    }
    let newDatas = [];
    let len = freeDatas.length;
    if(len>0){
      if(this.addNodePosition==-1){
        newDatas = [...freeDatas,...arr];
      }else if(this.addNodePosition+1==len){
        newDatas = [...arr,...freeDatas];
      }else {
        freeDatas.forEach((item,index)=>{
          if(this.addNodePosition==(len-index-2)){
            newDatas = [...newDatas,item,...arr];
          }else {
            newDatas = [...newDatas,item];
          }
        })
      }

    }else {
      return arr;
    }
    return newDatas;
  }
  @action
  deleteFreeDatas=(freeDatas=[])=>{
    let newFreeDatas = [];
    let len = freeDatas.length;
    freeDatas.map((item,index)=>{
      if(index!=(len-1-this.deleteNodePosition)){
        newFreeDatas = [...newFreeDatas,item];
      }
    })
    return newFreeDatas;
  }

  @action
  generateParams = (freeNodeList,params={},index)=>{
    let {ids,names,datas=[]} = toJS(this.selectedPersons);
    let len = freeNodeList.length;
    if(index<len){
      if(_.isEmpty(params)){
        let newParams = freeNodeList[index];
        if(len>1){
          let {id} = freeNodeList[index+1];
          newParams = {...newParams,preid:id}
        }
        return this.generateParams(freeNodeList,newParams,index+1);
      }else {
        let newParams = {...freeNodeList[index],next:params,nextid:params["id"],hasNext:true};
        if(freeNodeList[index+1]){
          let {id} = freeNodeList[index+1];
          newParams = {...newParams,preid:id}
        }
        return this.generateParams(freeNodeList,newParams,index+1);
      }
    }
    return params;
  }

  @action
  saveAsTempSave = () => {
    let {rightMenu={},commonParam={},baseParam={}} = base.globalStore;
    const { iscreate,authSignatureStr,authStr,wfTestStr,belongTest, selectNextFlowPattern} = toJS(commonParam);
    const { iscnodefree,isFree,freeNode = {} ,isAllowNodeFreeFlow} = toJS(rightMenu);
    const {nodeid,workflowid,requestid,f_weaver_belongto_userid,f_weaver_belongto_usertype} = toJS(baseParam);
    let {szssz01={}} = rightMenu;
    let {createname="",createNodeid=""} = szssz01;
    let {name,type} =  toJS(this.modal);
    let params = {
      currentPostRequestId:"",
      currentPostWorkflowId:"",
      isFree,
      nodeid,
      workflowid,
      requestid,
      templateid: -1,
      isAllowNodeFreeFlow,
      f_weaver_belongto_userid,
      f_weaver_belongto_usertype,
      wfTestStr,
      authSignatureStr,
      authStr,
      belongTest,
      isFromHtmlPage: true,
      showForecastNode:"",
      maxGroupNum: this.maxGroupNum-1,
      chartDatas:JSON.stringify(toJS(this.freeNodeDatas)),
      deleteIds:"",
      type,
      name,
      method:"template"
    };
    API.saveFreeNodeInfo(params).then(result=>{
      const { success = false , id = '',isRepeat = false} = result;
      if(!success) {
        message.destroy();
        if(isRepeat) {
          message.warning("名称\"已存在，请重新输入！");
        } else {
          message.error("保存失败！");
        }
      } else {
        this.showSaveModalDialog = false;
        this.modal = {name:"",type:"0"};
        message.success("保存成功！");
      }
    })
  }


  @action
  getFlowTemplateList=()=>{
    if (_.isEmpty(toJS(this.modelAdCondition))) {
      API.getAddTemplateBaseData().then((result) => {
        const {advanceCondition = {}, addTemplateTabs = [], templateBaseInfo = [], addShareForm = {}} = result;
        // const addCondition = [{
        //     items: advanceCondition
        // }];
        const addCondition = [advanceCondition];
        this.modelAdCondition = addCondition;
        this.importModelForm.setCondition(addCondition);
        this.importModelForm.initFormFields(addCondition);
      });
    } else {
      this.importModelForm.resetConditionValue();
    }
    this.searchExistedModelList();
  }
  @action
  searchExistedModelList=()=>{
    let postParams = {
      isModelImport: 1,
      wfform:1
    };
    const formParams = this.importModelForm.getFormParams();
    postParams = {...postParams,...formParams};
    API.getFlowTemplateList(postParams).then(result=>{
      const {sessionkey = ''} = result;
      this.importModalStore.getDatas(sessionkey, 1, "");
    })
  }

  @action
  postImportModelDatas=(params)=>{
    this.loading = true;
    this.showImportModalDialog = false;
    let {rightMenu={},commonParam={},baseParam={}} = base.globalStore;
    const { iscreate,authSignatureStr,authStr,wfTestStr,belongTest, selectNextFlowPattern} = toJS(commonParam);
    const { iscnodefree,isFree,freeNode = {} ,isAllowNodeFreeFlow} = toJS(rightMenu);
    const {nodeid,workflowid,requestid,f_weaver_belongto_userid,f_weaver_belongto_usertype} = toJS(baseParam);
    //手动切换过当前节点的流转结后设置项，则取设置，否则取默认值 流转至下一节点
    let postParams = {
      requestid,
      templateid:-1,
      freeStartNodeid: this.freeStartNodeid,
      freeEndNodeid: this.freeEndNodeid
    };
    postParams = {...postParams, ...params};
    API.importFromTemplate(postParams).then((result) => {
      this.loading = false;
      this.initFreeNode(result);
    });
  }

  @action
  onOperatesClick=(record,index,operate,flag)=>{
    const {Modal,message} = getAntd();
    let _that = this;
    if(true){
      Modal.confirm({
        title: "信息确认",
        content: `是否确认删除当前模板`,
        onOk: () => {
          let params = {
            delids: record.id
          }
          API.deleteTemplate(params).then(data=>{
            _that.searchExistedModelList();
          })
        },
        okText: "确定",
        okCancel : () => {},
      });

    }
  }

}